package com.mol.market.community;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.community.FriendsterLoginTask.FriendsterUser;

public class FriendsterLoginTask extends AsyncTask<Void, Void, FriendsterUser>{
	
	public static final int METHOD_GET_USER = 0;
    private String userName;
    private String password;
    private ApiRequestListener listener;
	
	public FriendsterLoginTask(Context context, String userName,
			String password, ApiRequestListener listener) {
		this.userName = userName;
		this.password = password;
		this.listener = listener;
	}

	/**
     * FRIENDSTER API地址
     */
    public static final String API_HOST_FRIENDSTER =
    		"https://api.friendster.com/oauth/";
	
	private static String LOGIN_FRIENDSTER_URL = API_HOST_FRIENDSTER + "authorize";

	private static String FRIENDSTER_USER_INFO_URL = API_HOST_FRIENDSTER + "query/user";

	private String login() throws Exception {

		try {
			// 创建连接
			URL url = new URL(LOGIN_FRIENDSTER_URL);
			trustAllHttpsCertificates();
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setRequestProperty("Accept", "*/*");
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");

			connection.connect();

			// POST请求
			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());
			// friendsterstore@yahoo.com qwe123rty
			out.writeBytes("client_id=041bf56edac05540f631f57cdba5574a&grant_type=password&username=" + userName + "&"
					+ "scope=offline_access+query+avatar_info+messaging+profile_update&password=" + password 
					+ "&client_secret=5781a9a99d23688c03a5984b00f4c4ff");
			out.flush();
			out.close();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			System.out.println("============" + sb + "============");
			reader.close();
			// 断开连接
			connection.disconnect();
			JSONObject jsonObject = new JSONObject(sb.toString());
			String token = (String) jsonObject.get("access_token");
			System.out.println(token);
			return token;
		} catch (MalformedURLException e) {
			return null;
		} catch (UnsupportedEncodingException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	private static void trustAllHttpsCertificates() throws Exception {
		javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
		javax.net.ssl.TrustManager tm = new miTM();
		trustAllCerts[0] = tm;
		javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
				.getInstance("SSL");
		sc.init(null, trustAllCerts, null);
		javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
				.getSocketFactory());
	}

	static class miTM implements javax.net.ssl.TrustManager,
			javax.net.ssl.X509TrustManager {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public boolean isServerTrusted(
				java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public boolean isClientTrusted(
				java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public void checkServerTrusted(
				java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}

		public void checkClientTrusted(
				java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}

	}

	static HostnameVerifier hv = new HostnameVerifier() {
		public boolean verify(String urlHostName, SSLSession session) {
			System.out.println("Warning: URL Host: " + urlHostName + " vs. "
					+ session.getPeerHost());
			return true;
		}
	};

	public FriendsterUser getUserInfo(String token) throws Exception {

		try {
			// 创建连接
			URL url = new URL(FRIENDSTER_USER_INFO_URL);
			trustAllHttpsCertificates();
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("GET");
			connection.setUseCaches(false);
			connection.setRequestProperty("Accept", "*/*");
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Authorization", "Bearer " + token);

			connection.connect();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			reader.close();
			// 断开连接
			connection.disconnect();
			JSONObject jsonObject = new JSONObject(sb.toString());
			JSONArray userArray = jsonObject.getJSONArray("user");
			JSONObject user = (JSONObject) userArray.get(0);
			long id = user.getLong("id");
			String email = user.getString("email");
			FriendsterUser friendsterUser = new FriendsterUser();
			friendsterUser.uid = id;
			friendsterUser.userName = email;
			return friendsterUser;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static class FriendsterUser{
		public long uid;
		public String userName;
	}

	@Override
	protected FriendsterUser doInBackground(Void... arg0) {

		try {
			String token = login();
			if(TextUtils.isEmpty(token)) {
				return null;
			} else {
				return getUserInfo(token);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(FriendsterUser result) {
		super.onPostExecute(result);
		if (result == null) {
			listener.onError(METHOD_GET_USER, 0);
		} else {
			listener.onSuccess(METHOD_GET_USER, result);
		}
	}
}